<script setup>
import { useUserStore } from "@/stores/counter";
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from '@element-plus/icons-vue';
import { useRouter } from "vue-router";
import { getUserInfo, updateUserInfo } from "@/api/user";
import { secureInvoke, secureInvoke2 } from "@/api/test";

const activeMenu = ref('user-info');

const userStore = useUserStore();
const userInfo = userStore.userInfo
const accessToken = userStore.accessToken;
const router = useRouter();
const testInput = ref('');

const handleAvatarSuccess = (response) => {
    userStore.setAvatar(response.data);
    ElMessage.success('头像上传成功');
};

const beforeAvatarUpload = (file) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!');
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
    }
    return isJPG && isLt2M;
};

const updateError = (err) => {
    ElMessage.error(err.message);
};

const saveChanges = async () => {
    await updateUserInfo(userInfo)
    ElMessage.success('信息已更新');
};

const logout = () => {
    userStore.removeTokens();
    router.push('/login');
};

const getuserInfoFn = async () => {
    try {
        const res = await getUserInfo(userStore.userId);
        if (res.data && res.data.data) {
            userStore.setUserInfo(res.data.data);
        } else {
            console.error('Unexpected response structure:', res);
        }
    } catch (error) {
        console.error('Failed to fetch user info:', error);
    }
}

const sendTestMessage = async () => {
    try {
        const res = await secureInvoke(testInput.value);
        ElMessage.success('消息发送成功');
    } catch (error) {
        ElMessage.error('消息发送失败');
    }
};

const sendTestMessage2 = async () => {
    try {
        const res = await secureInvoke2(testInput.value);
        ElMessage.success('消息发送成功');
    } catch (error) {
        ElMessage.error('消息发送失败');
    }
};

getuserInfoFn()

</script>

<template>
    <el-container>
        <el-aside width="200px">
            <el-menu :default-active="activeMenu" @select="activeMenu = $event">
                <el-menu-item index="user-info">个人信息</el-menu-item>
                <el-menu-item index="badges">勋章</el-menu-item>
                <el-menu-item index="test">测试</el-menu-item>
            </el-menu>
        </el-aside>
        <el-main>
            <div v-if="activeMenu === 'user-info'">
                <h2>个人信息</h2>
                <el-upload
                    class="avatar-uploader"
                    action="http://127.0.0.1:8080/avatarFile"
                    :show-file-list="false"
                    :headers="{ Authorization: 'Bearer ' + accessToken }"
                    :on-success="handleAvatarSuccess"
                    :on-error="updateError"
                    :before-upload="beforeAvatarUpload"
                >
                    <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
                    <Plus v-else class="avatar-uploader-icon" />
                </el-upload>
                <el-form :model="userInfo" label-width="80px">
                    <el-form-item class="setting-name" label="昵称">
                        <el-input v-model="userInfo.name"></el-input>
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-radio-group v-model="userInfo.sex">
                            <el-radio :value="1">男</el-radio>
                            <el-radio :value="0">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="saveChanges">确定修改</el-button>
                        <el-button type="danger" @click="logout">退出登录</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div v-else-if="activeMenu === 'badges'">
                <h2>勋章</h2>
                <div class="badges">
                    <div class="badge" v-for="n in 6" :key="n">勋章{{ n }}</div>
                </div>
            </div>
            <div v-else-if="activeMenu === 'test'">
                <h2>本地消息表测试</h2>
                <el-form label-width="80px">
                    <el-form-item label="输入框">
                        <el-input v-model="testInput"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="sendTestMessage">测试按钮</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="sendTestMessage2">测试按钮2</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-main>
    </el-container>
</template>

<style lang="scss" scoped>
.avatar-uploader {
    display: inline-block;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    overflow: hidden;
    position: relative;
    cursor: pointer;
    border: 1px dashed #d9d9d9;
    margin-bottom: 20px;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.avatar {
    width: 100%;
    height: 100%;
    display: block;
    border-radius: 50%;
}

.badges {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.badge {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-color: #f2f2f2;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #666;
}

.setting-name {
    max-width: 300px;
}
</style>